﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

namespace AudioEffectBox
{
    public class Audio16MixStream : Audio16CompositionStream
    {
       
        protected int _invertPercentage;
        protected int _percentage;
        public Audio16MixStream(Stream secondaryInput, int percentage, Stream outputStream) : base(secondaryInput,outputStream)
        {
            this.Percentage = percentage;
        }


        public int Percentage { get { return _percentage; } set 
        { if ((value < 0) || (value > 100)) throw new ArgumentException("Percentage must be between 0 and 100");
        lock (this)
        {
            _percentage = value; _invertPercentage = 100 - value;
        }
        }
        }
      
        
        public override void Write(byte[] buffer, int offset, int count)
        {
            lock (this)
            {
                if ((Percentage == 0)||!IsEnabled)
                {
                    OutPut.Write(buffer, offset, count);
                    return;
                }
                if (Percentage == 100)
                {
                    byte[] _secondBuffer = new byte[buffer.Length];
                    SecondInput.Read(_secondBuffer, 0, (count - offset));
                    OutPut.Write(_secondBuffer, 0, _secondBuffer.Length);
                    return;
                }
                MemoryStream _buffer = new MemoryStream(buffer, offset, count);
                BinaryReader _reader = new BinaryReader(_buffer);
                int _totalSamples = count / 2;
                while (_totalSamples != 0)
                {
                    Int16 _sample = (Int16)((_reader.ReadInt16() * _invertPercentage + _secondReader.ReadInt16() * _percentage) / 100);
                    _writer.Write(_sample);
                    _totalSamples--;
                }
            }
        }
    }
}
